class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {
    private int max = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        deep(root);
        return max;
    }

    private int deep(TreeNode root) {
        if (root != null) {
            int left = deep(root.left);
            int right = deep(root.right);
            int res = left + right;
            if (res > max) {
                max = res;
            }
            return (left > right ? left : right) + 1;
        }
        return 0;
    }
}